import Vue from 'vue'
import Vuex from 'vuex'

import {HubConnection} from '@/common/signalr.js'
// 引入猿哥APP的store
import brother from './modules/brother.js'
// 引入青猿驿站APP的store
import shop from './modules/shop.js'

Vue.use(Vuex)

let lifeData = {};

try{
	// 尝试获取本地是否存在lifeData变量，第一次启动APP时是不存在的
	lifeData = uni.getStorageSync('lifeData');
}catch(e){
	
}

// 需要永久存储，且下次APP启动需要取出的，在state中的变量名
let saveStateKeys = ['Authorization', 'userdetail', 'exp', 'userType', 'operatorid', 'franchiseId','storeId'];

// 保存变量到本地存储中
const saveLifeData = function(key, value){
	// 判断变量名是否在需要存储的数组中
	if(saveStateKeys.indexOf(key) != -1) {
		// 获取本地存储的lifeData对象，将变量添加到对象中
		let tmp = uni.getStorageSync('lifeData');
		// 第一次打开APP，不存在lifeData变量，故放一个{}空对象
		tmp = tmp ? tmp : {};
		tmp[key] = value;
		// 执行这一步后，所有需要存储的变量，都挂载在本地的lifeData对象中
		uni.setStorageSync('lifeData', tmp);
	}
}

const store = new Vuex.Store({
	modules:{
		brother,
		shop
	},
	state: {
		webSetting: {
			id: 0,
			commissionsetting:{
				user:{
					openentry: true
				}
			}
		},
		Authorization: '',
		exp: 0,
		userdetail: {
			Authorization: "",
			exp: "",
			franchiseId: "",
			operatorid: "",
			storeId: "",
			userType: -1,
			// userdetail: {
			// 	id: 0, 
			// 	bindinfo: {
			// 		operator: {}, 
			// 		databoardcity: [],
			// 	},
			// }
		},
		operatorid: 0,//运营商id
		storeId: 0, //站点id
		franchiseId: 0, //当前加盟商id
		userType: 1, //系统或未登录 = -1,用户 = 1,单位 = 2（废弃）,小哥 = 3,驿站 = 4,后台管理员 = 5,业务员 = 6,打包站 = 7,
		connection: null,
		productItem: {}, //临时保存所选的可回收物，用于编辑设置
	},
	mutations: {
		$uStore(state, payload) {
			// 判断是否多层级调用，state中为对象存在的情况，诸如user.info.score = 1
			let nameArr = payload.name.split('.');
			let saveKey = '';
			let len = nameArr.length;
			if(len >= 2) {
				let obj = state[nameArr[0]];
				for(let i = 1; i < len - 1; i ++) {
					obj = obj[nameArr[i]];
				}
				obj[nameArr[len - 1]] = payload.value;
				saveKey = nameArr[0];
			} else {
				// 单层级变量，在state就是一个普通变量的情况
				state[payload.name] = payload.value;
				saveKey = payload.name;
			}
			// 保存变量到本地，见顶部函数定义
			saveLifeData(saveKey, state[saveKey])
		},
		//网站信息
		setWebSetting(state, setting) {
			state.webSetting = setting
		},
		setLoadWebSetting(state, status) {
			state.loadWebSetting = status
		},
		setUserdetail(state, status){
			state.userdetail = status
		},
		setAuthorization(state, status){
			state.Authorization = status
		},
		setProductItem(state, status){
			state.productItem = status
		}
	},
	actions:{
		getWebSetting({
			commit,
			state
		}) {
			return new Promise((resolve) => {
				// if(state.webSetting.id > 0){
				// 	resolve(state.webSetting)
				// 	return
				// }
				Vue.prototype.$u.get('/Operator/Detail').then((res) => {
					let data = res
					if(data.sitelogoimg){
						data.sitelogoimg = Vue.prototype.fileURL + data.sitelogoimg
					}
					if(data.adminlogoimg){
						data.adminlogoimg = Vue.prototype.fileURL + data.adminlogoimg
					}
					if(data.wxqrcode){
						data.wxqrcode = Vue.prototype.fileURL + data.wxqrcode
					}
					commit('setWebSetting', data)
					resolve(data)
				}).catch(error => {
					resolve({
						error: '系统出错了,请稍后再尝试访问'
					})
				})
			});
		},
		getDetails({
			commit,
			state
		}) {
			return new Promise((resolve,reject) => {
				if(!uni.getStorageSync('lifeData') || uni.getStorageSync('lifeData').Authorization == '' || uni.getStorageSync('lifeData').userdetail.id == 0){
					reject()
					return
				}
				Vue.prototype.$u.get('/User/Detail').then((res) => {
					// 需要重连时重新登录
					// if(res.refresh == true){
					// 	uni.showToast({
					// 		icon: 'none',
					// 		title: '登录已失效，请重新登录'
					// 	})
					// 	uni.removeStorageSync('lifeData');
						
					// 	commit('setAuthorization', '')
					// 	commit('setUserdetail', {userid: 0})
					// 	reject()
					// }else{
						saveLifeData('userdetail',res)
						commit('setUserdetail', res)
						// console.log('成功获取用户详情：',res)
						resolve(res)
					// }
				}).catch(()=>{
					reject()
				})
			});
		},
		setUploadPara({
			commit,
			state
		}, data) {
			Vue.prototype.$u.get('/api/upload').then((res) => {
				data.OSSAccessKeyId = res.ossaccesskeyid;
				data.policy = res.policy;
				data.Signature = res.signature;
				data.host = res.host;
				data.dir = res.dir;
				data.expire = res.expire;
				data.callback = res.callback;
			});
		},
		// 在线推送信息
		signalrConnection({
			commit,
			state,
			dispatch
		}) {
			if(state.connection != null || state.Authorization == ''){
				return
			}
			state.connection = new HubConnection();
			console.log('ws心跳间隔时间',state.connection.timeInterval)
			console.log('ws连接状态',state.connection.openStatus)
			//注意：这里的Vue.prototype.baseURL不是wss或ws，是https或http
			state.connection.start(`${Vue.prototype.baseURL}/pushed`, {
				Terminal: 'WX',
				access_token: state.Authorization
			});
			
			state.connection.onOpen = res => {
				uni.showToast({
					title: '成功开启连接',
					icon:'none'
				});
				// state.connectionState = true
			}
			
			state.connection.onClose = res => {
				// uni.showToast({
				// 	title: '连接已关闭',
				// 	icon:'none'
				// });
				// state.connectionState = false
			}
			
			state.connection.onReconnect = res =>{
				console.log('尝试重新连接...')
				state.connection = new HubConnection();
				state.connection.start(`${Vue.prototype.baseURL}/pushed`, {
					Terminal: 'WX',
					access_token: state.Authorization
				});
			}
			
			state.connection.receive = msgData => {
				// 此处做一个防抖处理，以防重复连接websocket时同时触发多次方法
				uni.$u.throttle(()=>{
					// console.log('connection.receive',msgData,new Date())
					if (msgData.type === 1 && msgData.target == "reload") {
						console.log('收到重连要求')
						state.connection = new HubConnection();
						state.connection.start(`${Vue.prototype.baseURL}/pushed`, {
							Terminal: 'WX',
							access_token: state.Authorization
						});
					}
					if (msgData.type === 1 && msgData.target == "outlogin") {
						console.log('收到重新登录要求')
						state.connection.close()
						uni.showModal({
							content: '账号异常请重新登录',
							showCancel: false,
							success: (res)=> {
								if (res.confirm) {
									uni.removeStorageSync('lifeData');
									uni.navigateTo({
										url: '/pages/login/login'
									})
								}
							}
						})
					}
				},100)
			}
		},
	}
})

export default store